//
//  ComposeView.swift
//  weibobbaj
//
//  Created by Tiffany宝 on 16/4/25.
//  Copyright © 2016年 Tiffany. All rights reserved.
//

import UIKit
import pop

class ComposeView: UIView {
    
    var target: UIViewController?
    
    //懒加载模型数组
    lazy var array:[MenuInfoModel] = {
        
        return self.itemInfo()
    }()
    
    //初始化按钮空数组
    var menuButtons: [ComposeMenuButton] = []
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        backgroundColor = UIColor.darkGrayColor()
        frame.size = UIScreen.mainScreen().bounds.size
        
        let imageCut = UIImage.getCurrentImage().applyLightEffect()
        //把图片保存至某个路径
        //首先要将图片转换成 data ,再进行存储
        //        let imageData = UIImagePNGRepresentation(imageCut)
        //        imageData?.writeToFile("/Users/Tiffanybbaj/Desktop/haha.png", atomically: true)
        
        let imageCutView: UIImageView = UIImageView(image:imageCut)
        //添加控件
        addSubview(imageCutView)
        addSubview(sloganImageView)
        
        //添加约束
        sloganImageView.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(100)
            make.centerX.equalTo(self)
        }
        
        //添加按钮
        addMenuButton()
    
    }
    
    private func addMenuButton(){
        
//        let array = itemInfo()
        
        let menuBtnW: CGFloat = 80
        let menuBtnH: CGFloat = 110
        let margin = (SCREENW - 3 * menuBtnW ) / 4
        
        for (i,value) in array.enumerate(){
            
            let button = ComposeMenuButton()
            
            //给按钮添加监听事件
            button.addTarget(self, action: "menuButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            
            //给按钮打tag
            button.tag = i
            
            button.titleLabel?.font = UIFont.systemFontOfSize(14)
            
            button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
            
            button.setTitle(value.title, forState: UIControlState.Normal)
            
            button.setImage(UIImage(named: value.icon!), forState: UIControlState.Normal)
            //        button.sizeToFit()
            //        button.frame = CGRectMake(100, 0, 80, 110)
            
            button.frame.size = CGSizeMake(menuBtnW,menuBtnH)
            
            //计算行列索引
            let row = i / 3
            let col = i % 3
            
            //调整位置
            button.frame.origin.x = CGFloat(col) * menuBtnW + (CGFloat(col) + 1) * margin
            button.frame.origin.y = CGFloat(row) * menuBtnW + CGFloat(row) * 30 + SCREENH
            
            addSubview(button)
            
            //加入按钮数组
            menuButtons.append(button)
        }
    }
    
    // MARK: - 把控制器传过来
    func show(target: UIViewController){
        
        //添加上去
        target.view.addSubview(self)
        
        self.target = target
    }
    
    //点击按钮触发的方法
    @objc private func menuButtonClick(button: UIButton){
        
        UIView.animateWithDuration(0.25, animations: { () -> Void in

            for value in self.menuButtons{
                
                value.alpha = 0.01
                if value == button{
                    //放大所点击的按钮
                    value.transform = CGAffineTransformMakeScale(2, 2)
                }else{
                    //缩小其他的按钮
                    value.transform = CGAffineTransformMakeScale(0.01, 0.01)
                }
            }
            
            }) { (_) -> Void in
                
                //测试复原
//                UIView.animateWithDuration(0.25, animations: { () -> Void in
//                    
//                    for value in self.menuButtons{
//                        
//                        value.alpha = 1
//                        value.transform = CGAffineTransformIdentity
//                    }
//        
//                })
                
                //弹控制器
                //取出模型
                let model = self.array[button.tag]
                
                //swift 中通过类名初始化对象
//                let className = NSStringFromClass(ComposeViewController.self) ---> weibobbaj.ComposeViewController
//                let clazzName = NSClassFromString("ComposeViewController") ---> nil
                let type = NSClassFromString(model.className!) as! UIViewController.Type
                let composeVc = type.init() // ComposeViewController()
                
//                let composeVc = ComposeViewController()
                self.target?.presentViewController(UINavigationController(rootViewController: composeVc), animated: true, completion: { () -> Void in
                    
                    self.removeFromSuperview()
                })
        }
        
    }
    
    private func itemInfo() -> [MenuInfoModel]{
        
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
        let array = NSArray(contentsOfFile: path)!
        
        //创建临时数组
        var tempArr: [MenuInfoModel] = []
        
        for value in array{
            
            let model = MenuInfoModel(dic: value as! [String : AnyObject])
            tempArr.append(model)
        }
        return tempArr
    }
    
    // UIView 中将要显示视图的生命周期方法 --> 类似于 控制器中的 ViewWillAppear 方法
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        self.alpha = 0.01
        UIView.animateWithDuration(0.5, animations: { () -> Void in
            
            self.alpha = 1
        })
    }
    
    // *** 等视图显示出来后再执行动画
    override func didMoveToSuperview() {
        
        super.didMoveToSuperview()
        
                //执行动画
        for (i,value) in menuButtons.enumerate(){
            
            animation(value, i: i, isUp: false)
            //初始化动画对象
            //            let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            //            //设置ToValue **** 用 NSValue 包装结构体
            //            anim.toValue = NSValue(CGPoint: CGPoint(x: value.center.x, y: value.center.y - 300))
            //            //设置动画的属性
            //            anim.springSpeed = 10
            //            anim.springBounciness = 8
            
            //方法一
            //            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(Double(0.025 * Double(i)) * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in
            //
            //                //添加动画
            //                value.pop_addAnimation(anim, forKey: nil)
            //
            //            })
            
            //方法二
            //            anim.beginTime = Double(i) * 0.025 + CACurrentMediaTime()
            //            value.pop_addAnimation(anim, forKey: nil)
            
        }
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        print("view被销毁了")
        //执行动画
        for (i,value) in menuButtons.reverse().enumerate(){
            
            animation(value, i: i, isUp: true)
            //初始化动画对象
            //            let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            //            //设置ToValue **** 用 NSValue 包装结构体
            //            anim.toValue = NSValue(CGPoint: CGPoint(x: value.center.x, y: value.center.y + 300))
            //            //设置动画的属性
            //            anim.springSpeed = 10
            //            anim.springBounciness = 8
            
            //方法一
            //            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(Double(0.025 * Double(i)) * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in
            //
            //                //添加动画
            //                value.pop_addAnimation(anim, forKey: nil)
            //
            //            })
            
            //方法二
            //            anim.beginTime = Double(i) * 0.025 + CACurrentMediaTime()
            //            value.pop_addAnimation(anim, forKey: nil)
        }
        self.alpha = 1
        UIView.animateWithDuration(0.5, animations: { () -> Void in
            
            self.alpha = 0.01
        })
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(Double(0.4) * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            
            self.removeFromSuperview()
        }
    }
    
    func animation(value: UIButton,i: Int,isUp: Bool){
        
        //初始化动画对象
        let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        //设置ToValue **** 用 NSValue 包装结构体
        anim.toValue = NSValue(CGPoint: CGPoint(x: value.center.x, y: value.center.y + (isUp ? 300 : -300)))
        //设置动画的属性
        anim.springSpeed = 10
        anim.springBounciness = 8
        
        //方法一
        //            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(Double(0.025 * Double(i)) * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in
        //
        //                //添加动画
        //                value.pop_addAnimation(anim, forKey: nil)
        //
        //            })
        
        //方法二
        anim.beginTime = Double(i) * 0.025 + CACurrentMediaTime()
        value.pop_addAnimation(anim, forKey: nil)
    }
    
    //截取屏幕(已抽取到分类)
    //    private func getCurrentImage() -> UIImage{
    //
    //        let window = UIApplication.sharedApplication().keyWindow
    //        //开启图形上下文
    //        // 参数3： 传入0，代表是屏幕真实大小截图，传1的话，以点坐标的大小
    //        UIGraphicsBeginImageContextWithOptions(window!.bounds.size, false, 1)
    //
    //        //把屏幕内容渲染到图形上下文
    //        window?.drawViewHierarchyInRect(window!.bounds, afterScreenUpdates: true)
    //
    //        //获取图片
    //        let image = UIGraphicsGetImageFromCurrentImageContext()
    //
    //        //关闭图形上下文
    //        UIGraphicsEndImageContext()
    //
    //        //返回图片
    //        return image
    //    }
    
    //懒加载
    private lazy var sloganImageView: UIImageView = UIImageView(image: UIImage(named: "compose_slogan" ))
    
}










